package com.qf.common;

import com.alibaba.fastjson.JSON;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Properties;

/**
 * @author sky
 * @date 2022-08-19
 */
@WebServlet(name = "DispatchServlet",urlPatterns = "/good",loadOnStartup = 1)
public class DispatchServlet extends HttpServlet {

    private ApplicationContext context;
    private Properties properties;
    @Override
    public void init() throws ServletException {
        super.init();
        context = new ClassPathXmlApplicationContext("classpath:beans.xml");
        properties = new Properties();
        ServletContext servletContext = this.getServletContext();
        try {
            properties.load(servletContext.getResourceAsStream("/WEB-INF/goods.properties"));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) {
        String path = request.getServletPath();
        String className = properties.getProperty(path);
        String methodName = request.getParameter("method");
        System.out.println("页面上请求的路劲是："+path);
        System.out.println("路径对应的类：" +className);
        System.out.println("执行类种的方法是：" +methodName);

        try {
            Class clazz = Class.forName(className);
            Object bean = context.getBean(clazz);
            Method method = clazz.getDeclaredMethod(methodName, HttpServletRequest.class);
            System.out.println(method+"--------------------------------------");
            Object invoke = method.invoke(bean, request);
            System.out.println(invoke);
            // 改变响应的格式  默认（html---> json）
            response.setContentType("text/json");
            // 改变响应的字符集合
            response.setCharacterEncoding("utf-8");
            response.setHeader("Access-Control-Allow-Origin", "*");
            response.setHeader("Access-Control-Allow-Methods", "POST, GET, PUT, OPTIONS, DELETE");
            response.setHeader("Access-Control-Max-Age", "3600");
            response.setHeader("Access-Control-Allow-Headers", "x-requested-with, Content-Type");
            response.setHeader("Access-Control-Allow-Credentials", "true");
            response.getWriter().write(JSON.toJSONString(invoke));
        } catch (Exception e) {
          e.printStackTrace();
        }

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) {
        doPost(request,response);
    }
}
